package com.vito.framework.system.role.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vito.framework.base.controller.BaseController;
import com.vito.framework.base.exception.CommonException;
import com.vito.framework.system.menu.model.MenuBean;
import com.vito.framework.system.menu.service.impl.MenuTree;
import com.vito.framework.system.org.model.OrgBean;
import com.vito.framework.system.org.service.OrgManageService;
import com.vito.framework.system.role.model.RoleBean;
import com.vito.framework.system.role.service.RoleService;
import com.vito.support.ApiResponse;
import com.vito.support.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***************************************************************
 * Name: RoleAction.java Create At: 2010-04-22 Module: 角色管理 Description:
 * [系统管理-角色管理功能] Author zhaowentao
 * ------------------------------------------------------------ 修改历史 序号 日期 修改人
 * 修改原因 1 2
 ***************************************************************/
@RestController
@RequestMapping("${adminPath}/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private OrgManageService orgManageService;

    /**
     * Author:zhaorui Create At:2010-06-30 Description: 跳转到添加页面
     * 
     * @return String
     * @throws Exception
     */
    @PostMapping(value = "add", consumes = "application/json;charset=UTF-8")
    public ApiResponse add(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
	    String siId = (String) paramMap.get("cur_orgId");
	    paramMap.put("param_orgId", siId);
	    try {
		    List<OrgBean> orgList = orgManageService.getOrgManageList(paramMap);
		    return ApiResponse.ok(orgList);
	    } catch(CommonException e) {
		    e.printStackTrace();
		    return ApiResponse.of(e);
	    }
    }
    
    /**
     * Create At:   2017年9月27日
     * @author   ztshan
     * @param    
     * @return    
     * @description  ajax返回按照orgId查询的menuList
     */
    @PostMapping(value = "getRoleMenuList", consumes = "application/json;charset=UTF-8")
    public ApiResponse getRoleMenuList(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        String orgId = params.getString("orgId");
        String roleId = params.getString("roleId");
        if (StrUtil.isEmpty(orgId)) {
            return null;
        }
        String userId = (String) paramMap.get("cur_userId");
	    paramMap.put("param_userId", userId);
	    paramMap.put("param_orgId", orgId);
	    paramMap.put("param_roleId", roleId);
        List<MenuBean> roleMenuList = null;
      
        try {
        	roleMenuList= roleService.getMenuByRole(paramMap);
            if (roleMenuList != null && roleMenuList.size()<=0) {
            	roleMenuList = roleService.getRoleMenuForAddList(paramMap);
            }
            roleMenuList = MenuTree.buildDivMenuTreeData(roleMenuList);
	        return ApiResponse.ok(roleMenuList);
        } catch (CommonException e) {
	        e.printStackTrace();
	        return ApiResponse.of(e);
        }
    }
    
    /**
     * Author:zhaowentao Create At:2010-04-22 Description: [用户管理-查询用户列表]
     * 
     * @return String
     */
    @PostMapping(value = "getMenuByRole", consumes = "application/json;charset=UTF-8")
    public ApiResponse getMenuByRole(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

	    Map<String, Object> resMap = new HashMap<>();

        try {
            String roleId = params.getString("roleId");
            if (roleId == null || "".equals(roleId)) {
                return ApiResponse.of(ResultEnum.PARAMS_INVALID);
            }
	        paramMap.put("param_roleId", roleId);
            RoleBean roleBean = roleService.getById(roleId);
	        paramMap.put("param_orgId", roleBean.getOrgId());
            //List<MenuBean> list = roleService.getMenuByRole(paramMap);
	        paramMap.remove("param_orgId");
            List<OrgBean> orgList = orgManageService.getOrgManageList(paramMap);

            //resMap.put("roleMenuList", list);
	        resMap.put("roleBean", roleBean);
	        resMap.put("orgList", orgList);
	        return ApiResponse.ok(resMap);
        } catch (Exception e) {
	        return ApiResponse.of(e);
        }
    }
    
    /**
     * Author:zhaowentao Create At:2010-04-22 Description: [角色管理-删除角色信息]
     * 
     * @return String
     */
    @PostMapping(value = "delete", consumes = "application/json;charset=UTF-8")
    public ApiResponse delete(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
        	String roleId=params.getString("roleId");
        	String[] ids=roleId.split(",");
	        paramMap.put("ids", ids);
	    	String siId = (String) paramMap.get("cur_orgId");
			String userId=(String) paramMap.get("cur_userId");
	        paramMap.put("param_userId", userId);
	        paramMap.put("param_siId", siId);
            roleService.deleteRole(paramMap);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (Exception e) {
	        e.printStackTrace();
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:zhaowentao Create At:2010-04-22 Description: [用户管理-修改用户，保存用户信息]
     * 
     * @return String
     */
    @PostMapping(value = "edit", consumes = "application/json;charset=UTF-8")
    public ApiResponse edit(HttpServletRequest request, @RequestBody RoleBean roleBean) {
	    if(null == roleBean) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
	    String userId=super.getUserSession(request).getUserId();
        try {
	  
            roleBean.setUserId(userId);
            roleBean.setOrgId(roleBean.getOrgId());
	        roleService.editRole(roleBean);
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (Exception e) {
	        return ApiResponse.of(e);
        }
    }

    /**
     * Author:zhaowentao Create At:2010-04-22 Description: [用户管理-添加用户，保存用户信息]
     * 
     * @return String
     */
    @PostMapping(value = "addSave", consumes = "application/json;charset=UTF-8")
    public ApiResponse addSave(HttpServletRequest request, @RequestBody RoleBean roleBean) {
	    if(null == roleBean) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
//        	String siId = (String) paramMap.get("cur_orgId");
//    		String userId = (String) paramMap.get("cur_userId");
//	        paramMap.put("param_userId", userId);
//	        paramMap.put("param_siId", siId);
            roleService.addRole(roleBean);
	        return ApiResponse.ok(roleBean);
        } catch (Exception e) {
	        return ApiResponse.ok(e);
        }
    }

    /**
     * Author:zhaorui Create At:2010-04-22 Description: [系统管理-查询角色列表]
     * 
     * @return String
     */
    @PostMapping(value = "list", consumes = "application/json;charset=UTF-8")
    public ApiResponse list(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
		String siId = (String) paramMap.get("cur_orgId");
		String userId=(String) paramMap.get("cur_userId");
		String param_keyword=params.getString("param_keyword");
        try {
        	paramMap.put("param_keyword", param_keyword);
            paramMap.put("param_siId", siId);
            List<RoleBean> roleSet = roleService.getRoleList(paramMap);
            for (RoleBean role : roleSet) {
                if ("0".equals(role.getRoleType())) {
                    siId = "";
                    break;
                }
            }
	        paramMap.put("param_userId", userId);
            List<RoleBean> list = roleService.getRoleList(paramMap);
	        return ApiResponse.ok(list);
        } catch (Exception e) {
	        return ApiResponse.of(e);
        }
    }
    //角色管理查询已经授权的菜单
    @PostMapping(value = "getMenu", consumes = "application/json;charset=UTF-8")
    public ApiResponse getMenu(HttpServletRequest request, @RequestBody JSONObject params) {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }

        try {
            String roleId = params.getString("roleId");
            if (roleId == null || "".equals(roleId)) {
                return ApiResponse.of(ResultEnum.PARAMS_INVALID);
            }
	        paramMap.put("param_roleId", roleId);
	        paramMap.put("param_orgId", params.getString("orgId"));
            List<MenuBean> list = roleService.getMenuByRole(paramMap);
            
            list = MenuTree.buildDivMenuTreeData(list);
        	List<MenuBean> menuList=new ArrayList<MenuBean>();
            for(MenuBean item:list) {
            	for(MenuBean o:item.getChildren()) {
            		if(o.getSelectRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setSelectStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"selectRole");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"selectRole");
            			menuList.add(menuBean);
            		}
            		if(o.getAddRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setAddStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"addRoleitem.getMenuId()+"|"+o.getMenuId()+"|"+"addRole"");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"addRole");
            			menuList.add(menuBean);
            		}
            		if(o.getUpdateRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setUpdateStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"updateRole");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"updateRole");
            			menuList.add(menuBean);
            		}
            		if(o.getDeleteRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setDeleteStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"deleteRole");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"deleteRole");
            			menuList.add(menuBean);
            		}
            		if(o.getExportRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setExportStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"exportRole");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"exportRole");
            			menuList.add(menuBean);
            		}
            		if(o.getImportRole() == 1) {
            			MenuBean menuBean=new MenuBean();
            			//menuBean.setImportStr(item.getMenuId()+"|"+o.getMenuId()+"|"+"importRole");
            			menuBean.setMenuId(item.getMenuId()+"|"+o.getMenuId()+"|"+"importRole");
            			menuList.add(menuBean);
            		}
//            		if(!StrUtil.isEmpty(menuBean.getAddStr()) || !StrUtil.isEmpty(menuBean.getSelectStr())  || !StrUtil.isEmpty(menuBean.getDeleteStr()) || !StrUtil.isEmpty(menuBean.getUpdateStr()) || !StrUtil.isEmpty(menuBean.getImportStr()) || !StrUtil.isEmpty(menuBean.getExportStr())) {
//            			menuList.add(menuBean);
//                		o.setChildren(menuList);
//            		}
            	}
            }
	        return ApiResponse.ok(menuList);
        } catch (Exception e) {
	        return ApiResponse.of(e);
        }
    }
    //角色授权菜单
    @PostMapping(value = "roleMenuAuthorizat", consumes = "application/json;charset=UTF-8")
    public ApiResponse roleMenuAuthorizat(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
	    Map<String, Object> paramMap = super.getParamMap(request,params);
	    if(null == paramMap) {
		    return ApiResponse.of(ResultEnum.PARAMS_INVALID);
	    }
        try {
        	String roleId=params.getString("roleId");
        	RoleBean roleBean=roleService.getById(roleId);
        	List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
       	    String ids[] = idList.toArray(new String[idList.size()]);
       	    List<String> selectRole=new ArrayList<String>();
       	    List<String> addRole=new ArrayList<String>();
       	    List<String> updateRole=new ArrayList<String>();
       	    List<String> deleteRole=new ArrayList<String>();
       	    List<String> importRole=new ArrayList<String>();
       	    List<String> exportRole=new ArrayList<String>();
       	    if(ids != null && ids.length>0) {
    	    	for(int i=0;i<ids.length;i++) {
    		    	String menuStr=ids[i];
    		    	JSONObject json=JSONObject.parseObject(menuStr);
    		    	String str=json.getString("menuId");
    		    	if(str.contains("Role")) {
    		    		String[] roleArrAll=str.split("\\|");
    		    		if(!selectRole.contains(roleArrAll[0])) {
    		    			selectRole.add(roleArrAll[0]);
    		    		}
    		    		if(!addRole.contains(roleArrAll[0])) {
    		    			addRole.add(roleArrAll[0]);
    		    		}
    		    		if(!updateRole.contains(roleArrAll[0])) {
    		    			updateRole.add(roleArrAll[0]);
    		    		}
    		    		if(!deleteRole.contains(roleArrAll[0])) {
    		    			deleteRole.add(roleArrAll[0]);
    		    		}
    		    		if(!importRole.contains(roleArrAll[0])) {
    		    			importRole.add(roleArrAll[0]);
    		    		}
    		    		if(!exportRole.contains(roleArrAll[0])) {
    		    			exportRole.add(roleArrAll[0]);
    		    		}
    		    		//处理可见
    		    		if(str.contains("selectRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!selectRole.contains(roleArr[1])){
    		    				selectRole.add(roleArr[1]);
    		    			}
    		    		}
    		    		//处理添加
    		    		if(str.contains("addRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!addRole.contains(roleArr[1])){
    		    				addRole.add(roleArr[1]);
    		    			}
    		    		}
    		    		//处理修改
    		    		if(str.contains("updateRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!updateRole.contains(roleArr[1])){
    		    				updateRole.add(roleArr[1]);
    		    			}
    		    		}
    		    		//处理修改删除
    		    		if(str.contains("deleteRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!deleteRole.contains(roleArr[1])){
    		    				deleteRole.add(roleArr[1]);
    		    			}
    		    		}
    		    		//处理修改导入
    		    		if(str.contains("importRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!importRole.contains(roleArr[1])){
    		    				importRole.add(roleArr[1]);
    		    			}
    		    		}
    		    		//处理修改导入
    		    		if(str.contains("exportRole")) {
    		    			String[] roleArr=str.split("\\|");
    		    			if(!exportRole.contains(roleArr[1])){
    		    				exportRole.add(roleArr[1]);
    		    			}
    		    		}
    		    	}
    		    }
    	    	roleBean.setSelectRole( selectRole.toArray(new String[selectRole.size()]));
    	    	roleBean.setAddRole(addRole.toArray(new String[addRole.size()]));
    	    	roleBean.setExportRole(exportRole.toArray(new String[exportRole.size()]));
    	    	roleBean.setDeleteRole(deleteRole.toArray(new String[deleteRole.size()]));
    	    	roleBean.setImportRole(importRole.toArray(new String[deleteRole.size()]));
    	    	roleBean.setUpdateRole(updateRole.toArray(new String[deleteRole.size()]));
    	    	roleService.roleMenuAuthorizat(roleBean);
    	    }
	        return ApiResponse.ok(ResultEnum.OK);
        } catch (CommonException e) {
	        return ApiResponse.of(e);
        }
    }
}